<template>
  <BaseDialog :loading="loading" destroy-on-close @confirm="save" @close="close" confirmText="保存" v-model="isShow"
              :title="title">
    <el-form
        ref="formRef"
        :model="state.dataForm"
        :rules="rules"
        label-width="80px"
        @submit="save"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input clearable placeholder="请输入角色名称" v-model="state.dataForm.roleName"/>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-switch :active-value="1" :inactive-value="2" v-model="state.dataForm.enabled"/>
      </el-form-item>
      <el-form-item label="角色编号" prop="roleCode">
        <el-input clearable placeholder="请输入角色编号" v-model="state.dataForm.roleCode"/>
      </el-form-item>
      <el-form-item label="顺序字段" prop="orderNum">
        <el-input-Number :min="1" :max="999999999" v-model="state.dataForm.orderNum"/>
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">

import {reactive, ref} from "vue";
import {RoleModel} from "/@/api/system/model/RoleModel";
import {insertRole, updateRole} from "/@/api/system/RoleApi";

const emit = defineEmits(['load'])
const state = reactive({
  dataForm: {
    roleId: '',
    roleName: '',
    enabled: 1,
    roleCode: '',
    orderNum: 1,
  } as RoleModel
})

const formRef = ref()
const loading = ref(false)
const isShow = ref(false)
const title = ref("")
const init = (titleValue: string, data: RoleModel) => {
  if (data) {
    state.dataForm = data
  }
  title.value = titleValue
  isShow.value = true
}
/**
 * 保存角色
 */
const save = async () => {
  await formRef.value.validate()
  loading.value = true
  if (state.dataForm.roleId) {
    await updateRole(state.dataForm, () => {
      loading.value = false
    })
  } else {
    await insertRole(state.dataForm, () => [
      loading.value = false
    ])
  }
  emit('load')
  close()
}
/**
 * 关闭
 */
const close = () => {
  state.dataForm = {
    roleId: '',
    roleName: '',
    enabled: 1,
    roleCode: '',
    orderNum: 1,
  } as RoleModel
  isShow.value = false;
}

defineExpose({init})

const rules = {
  roleName: [
    {required: true, message: '角色名称不能为空', trigger: 'blur'},
    {min: 1, max: 64, message: '角色名称长度为1到64个字符', trigger: 'blur'}
  ],
  roleCode: [
    {required: true, message: '角色编号不能为空', trigger: 'blur'},
    {min: 1, max: 64, message: '角色编号长度为1到64个字符', trigger: 'blur'}
  ]
}
</script>

<style scoped>

</style>